package com.andy.qhb.game;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.RandomUtils;

import com.andy.qhb.QhbApplication;
import com.andy.qhb.dao.DaoUtils;
import com.andy.qhb.dao.vo.Where;
import com.andy.qhb.entity.UsrFabLog;
import com.andy.qhb.entity.UsrGroups;
import com.andy.qhb.game.task.TimerManager;
import com.andy.qhb.schd.BatchScheduler;
import com.andy.qhb.utils.DateUtil;
import com.andy.qhb.utils.GoConstant;
import com.andy.qhb.vo.HFriend;
import com.andy.qhb.vo.ShowMsg;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

public class Room implements Serializable{

	private static final long serialVersionUID = 1L;
	
	public static final List<Integer> LEI_VALUE = Lists.newArrayList(1,2,3,4,5,6,7,8,9);

	private int id;
	
	private int num;
	
	private double rate;
	
	private int low;
	
	private int high;
	
	private int uconut;
	
	private int type; // 1-扫雷，2-禁抢
	
	private UsrGroups groups;
	
	private Map<Long,GameUser> users = Maps.newConcurrentMap();
	
	private LoopList<ShowMsg> loopList = new LoopList<>();
	
	private volatile long lastFabTime = 0;
	
	public Room(int id) {
		this.id = id;
	}
	
	public Room(int id,int low,int high) {
		this.id = id;
		this.low = low;
		this.high = high;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public Collection<GameUser> users() {
		return users.values();
	}

	public void addUser(GameUser user) {
		this.users.put(user.getId(),user);
		user.setRoom(this);
		user.setMsgIndx(0);
		this.uconut++;
	}
	
	public void removeUser(GameUser user){
		this.users.remove(user.getId());
		user.setRoom(null);
		user.setMsgIndx(0);
		this.uconut--;
		if(this.uconut < 0) {
			this.uconut = 0;
		}
	}
	
	
	public int endIndx(){
		return loopList.endIndx();
	}
	
	public List<ShowMsg> subMsgs(int start,int end) {
		return loopList.subList(start, end);
	}
	
	public void addMsg(ShowMsg msg){
		loopList.add(msg);
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public int getLow() {
		return low;
	}

	public void setLow(int low) {
		this.low = low;
	}

	public int getHigh() {
		return high;
	}

	public void setHigh(int high) {
		this.high = high;
	}

	public int getUconut() {
		return uconut;
	}

	public void setUconut(int uconut) {
		this.uconut = uconut;
	}

	public double getRate() {
		return rate;
	}

	public void setRate(double rate) {
		this.rate = rate;
	}

//	public UsrGroups getGroups() {
//		return groups;
//	}

	public void setGroups(UsrGroups groups) {
		this.groups = groups;
		if(groups != null) {
			String[] attr = groups.getRemark().split("-");
			this.type = Integer.parseInt(attr[0]);
			int ci = Integer.parseInt(attr[1])-1;
			this.low = GameConf.roomCoinGroup1[ci*2];
			this.high = GameConf.roomCoinGroup1[ci*2+1];
			this.num = Integer.parseInt(attr[2]);
//			int muti = Integer.parseInt(attr[3].split(",")[0]);
			this.rate = GameConf.roomCoinGroup2[0][num-7]/10.0;
		}
	}
	
	public boolean isNorRoom() {
		return this.groups == null;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public void initRobot() {
		
		TimerManager.scheduleWithFixedDelay(()->{
			if(!QhbApplication.isStarted()) return null;
			// 超过一定时间没有发包则机器人发包
			if(System.currentTimeMillis() - lastFabTime > 12*1000) {
				int coin = RandomUtils.nextInt(low/10, high/10)*1000;
				Collections.shuffle(LEI_VALUE);
				int count = RandomUtils.nextInt(1, 4);
				int lei = 0;
				for(int i=0;i<count;i++) {
					lei = lei*10 + LEI_VALUE.get(i);
				}
				GameUtils.fab(RobotManager.getRobot(), coin, num, lei, this);
			}
			
			return null;
		}, 15*1000, 12*1000);
		
		if(type == GoConstant.GAME_TYPE_F) {
			initFl();
		}
	}

	// 重启后初始化上次发的红包
	private void initFl() {
		Long curTime = DateUtil.getCurrentTime();
		Long endTime = DateUtil.getCurrentDateLong();
		if(curTime > endTime+20*3600+30*60) {
			// 超过20:30取当天的
			endTime = endTime+20*3600+30*60;
		}else {
			// 否则取昨天20:30的
			endTime = endTime - 3*3600-30*60;
		}
		Long startTime = endTime - 11*3600-30*60;
		try {
			String sql = "select t.uid from usr_fab_log t where t.uid > 200000 and (t.create_time >= ? and t.create_time < ?)  " 
					+ " GROUP BY t.uid having sum(t.coin) >= 200000";
			List<Map<String, Object>> uids = DaoUtils.getListSql(sql, startTime,endTime);
			Set<Long> userids = Sets.newHashSet();
			uids.forEach((it)->{
				userids.add(MapUtils.getLong(it, "uid"));
			});
			Global.currFlUids = userids;
			
			QhbGame flGame = BatchScheduler.backFlgame();
			if(flGame == null) return;
			UsrFabLog fabLog = DaoUtils.getOne(UsrFabLog.class, Where.eq("room_id", id),Where.ge("create_time", endTime));
			GameUser creater = GameUtils.getUsrUser(fabLog.getUid());
			flGame.setCreater(creater);
			Global.addGame(flGame);
			
			ShowMsg showMsg = new ShowMsg(0, new HFriend(creater.getId(), creater.getNickName(), creater.getIcon()));
			Map<String,Object> gameData = Maps.newHashMap();
			gameData.put("pid", fabLog.getId());
			gameData.put("coin", fabLog.getCoin());
			gameData.put("num", fabLog.getNum());
			gameData.put("lei", fabLog.getRemark());
			showMsg.setMsg(gameData );
//			addMsg(showMsg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public GameUser creater() {
		return this.groups.creater();
	}

}
